package org.cogaen.demo.application;

import java.awt.Dimension;
import java.awt.event.KeyEvent;

import org.cogaen.demo.state.CreditsState;
import org.cogaen.event.Event;
import org.cogaen.event.EventListener;
import org.cogaen.event.EventManager;
import org.cogaen.input.KeyPressedEvent;
import org.cogaen.java2d.ComboScreen;
import org.cogaen.java2d.ScreenException;
import org.cogaen.logging.LoggingService;

public class ComboDemo implements EventListener {

	private static final String LOGGING_SOURCE = "CogaenDemo";
	private static final String APP_TITLE = "Cogaen Demo";
	private static final Dimension SIZE = new Dimension(800, 600);
	private static final boolean USE_MAIN_THREAD = false;
	private LoggingService logger;
	private GameApp gameApp;
	private ComboScreen screen;
	
	private ComboDemo() {
		this.screen = ComboScreen.createWindowed(SIZE.width, SIZE.height);
		this.screen.setTitle(APP_TITLE);
		this.gameApp = new GameApp( this.screen );
		this.logger = LoggingService.getInstance(this.gameApp.getCore());
		
		EventManager evtMngr = EventManager.getInstance( gameApp.getCore() );
		evtMngr.addListener(this, CreditsState.END_OF_CREDITS);
		evtMngr.addListener(this, KeyPressedEvent.TYPE);
	}
	
	public static void main(String[] args) {
		ComboDemo demo = new ComboDemo();
		
		if (USE_MAIN_THREAD) {
			demo.gameApp.run();			
		} else {
			Thread gameLoop = new Thread(demo.gameApp);
			gameLoop.start();			
		}
	}

	@Override
	public void handleEvent(Event event) {
		if (event.getType().equals( CreditsState.END_OF_CREDITS ) ) {
			System.exit(0);
		} else if (event.getType().equals(KeyPressedEvent.TYPE)) {
			KeyPressedEvent kpEvt = (KeyPressedEvent) event;
			switch (kpEvt.getKeyCode()) {
			case KeyEvent.VK_O:
				if (this.screen.isFullscreen()) {
					this.logger.logInfo(LOGGING_SOURCE, "switching to windowed mode");
				} else {
					this.logger.logInfo(LOGGING_SOURCE, "switching to full-screen mode");
				}
				switchScreenMode(!this.screen.isFullscreen());
				break;
				
			case KeyEvent.VK_W:
				this.logger.logInfo(LOGGING_SOURCE, "switching to windowed mode");
				switchScreenMode(false);
				break;
				
			case KeyEvent.VK_F:
				this.logger.logInfo(LOGGING_SOURCE, "switching to full-screen mode");
				switchScreenMode(true);
				break;
			}
		}
	}	
	
	private void switchScreenMode(boolean fullScreen) {
		try {
			this.screen.setFullscreen(fullScreen);
		} catch (ScreenException e) {
			LoggingService.getInstance(this.gameApp.getCore()).logError(LOGGING_SOURCE, e.getMessage());
		}
	}
}
